<?php

function fecha($date, $hora = false) {
    if (empty($date) || strstr($date, "0000-00-00")) {
        return "No disponible";
    }
    $string = "d/m/Y";
    if ($hora) {
        $string = "d/m/Y H:i";
    }
    return date($string, strtotime($date));
}

function fechaSQL($fecha) {
    if (empty($fecha)) {
        return "";
    }
    $array = explode("/", $fecha);
    if (is_array($array) && count($array) == 3) {
        return $array[2] . "-" . $array[1] . "-" . $array[0];
    }
    return "";
}

function crearSelect($name, $value, $array, $readonly=false) {
    if ($readonly) {
        return $array[$value];
    }
    $html = '<select name="' . $name . '">';
    $html.= '<option value=""></option>';
    foreach ($array as $key => $val) {
        $html.= '<option value="' . $key . '" ' . ($value == $key ? 'selected="selected"' : '') . '>' . $val . '</option>';
    }
    $html.= '</select>';
    return $html;
}

function crearInput($name, $value, $class, $readonly=false) {
    if ($readonly) {
        return $value;
    }
    return '<input type="text" class="' . $class . '" name="' . $name . '" value="' . $value . '" />';
}

function arrayFiltro($array_data) {
    $array = array();
    foreach ($array_data as $clave => $valor) {
        if (!empty($valor) && $clave != "_filter") {
            $clave = str_replace("-", ".", $clave) . ' LIKE';
            $valor = (strstr($clave, "fecha") || strstr($clave, "date") ? fechaSQL($valor) : $valor);
            $valor = (campoLike($clave) ? '%' . $valor . '%' : $valor);
            $array[$clave] = $valor;
        }
    }
    return $array;
}

function campoLike($campo) {
    $arrayNotLike = array("id", "numero", "number", "fecha", "date", "estado", "status");
    foreach ($arrayNotLike as $str) {
        if (strstr($campo, $str)) {
            return false;
        }
    }
    return true;
}

function getCodigo($id) {
    return "#" . sprintf("%08d", $id);
}

function viewField($label, $value) {
    echo '<div class="field">';
    echo '<label for="'.$label.'">'.$label.'</label>';
    echo '<span class="field">'.$value.'</span>';
    echo '</div>';
}